package naito_rescue.task.job;

import rescuecore2.standard.components.*;
import rescuecore2.standard.entities.*;
import rescuecore2.misc.geometry.*;
import rescuecore2.worldmodel.*;
import naito_rescue.task.*;
import naito_rescue.agent.*;
import naito_rescue.object.*;
import java.util.*;
import java.io.*;

public class ClearJob extends Job
{
	NAITOArea target;
	int       repairDistance;
	
	public ClearJob(NAITOHumanoidAgent owner, NAITOArea target){
		super(owner);
		this.target = target;
		this.repairDistance = owner.getMaxRepairDistance();
	}
	
	@Override
	public boolean isFinished(){
		String context = "ClearJob#isFinished";
		if(!target.isBlockadesDefined()){
			return true;
		}
		if(target.getBlockades() != null && !(target.getBlockades().isEmpty())){
			return false;
		}else{
			return true;
		}
	}
	
	@Override
	public void act(){
		List<Blockade> blockades = new ArrayList<Blockade>();
		if(target.getBlockades() != null){
			for(EntityID bID : target.getBlockades()){
				Blockade b = (Blockade)(model.getEntity(bID));
				blockades.add(b);
			}
		}else{
			return;
		}
		int x = owner.getX();
		int y = owner.getY();
		for(Blockade blockade : blockades){
			int distance = owner.findDistanceTo(blockade, x, y);
			if(distance < repairDistance){
				owner.clear(blockade.getID());
				return;
			}
		}
		
		//logger.info("Move to far Blockade.");
		int minDistance = Integer.MAX_VALUE;
		Blockade targetBlockade = null;
		for(Blockade blockade : blockades){
			int distance = owner.findDistanceTo(blockade, x, y);
			if(distance < minDistance){
				targetBlockade = blockade;
				minDistance = distance;
			}
		}
		if(targetBlockade != null){
			int targetX = targetBlockade.getX();
			int targetY = targetBlockade.getY();
			owner.move(owner.getRouter().getRoute(target.getID()), targetX, targetY);
		}
		//logger.info("**** ClearJob.act(); end. ****");
	}
	
	@Override
	public String toString(){
		return "ClearJob(" + target.getID().getValue() + ", " + isFinished() + ")";
	}
}
